//
//  AppDelegate.swift
//  SurfEasy
//
//  Created by 薛永伟 on 2019/9/12.
//  Copyright © 2019 XueYongWei. All rights reserved.
//

import UIKit
@_exported import SnapKit
@_exported import SwiftyJSON


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    /// 启动时的推送内容（便于合适时机进行处理）
//    static var launchNotification:UNNotification?
    
    
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        /// runtime开启方法交换
        YRRuntime.letsSwizzle()
        /// 信任所有的https证书
        API.Reachability.trustAllChallenge()
        
        setupRootController()
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

//MARK: - --------------AppEntrance--------------
extension AppDelegate {
    
    /// 初始化根控制器
    func setupRootController() {
        
        let newWindow = UIWindow()
        newWindow.backgroundColor = UIColor.white
        window = newWindow
        
        loadAppEntrance()
        
//        requestLaunchDiagram()
//
//        if let cacheAD = loadSplashAD(){//有广告，去展示
//            loadLaunchAD(ad: cacheAD)
//        }else{//直接加载根控制器
//            loadAppRoot()
//        }
    }
    
    /// 加载app的入口
    func loadAppEntrance(){
        
        let rootVC = RootViewController()
        window?.rootViewController = rootVC
        window?.makeKeyAndVisible()
    }
    
    /// 加载开屏广告
    func loadLaunchAD(ad: LaunchADViewController.ADModel){
        
//        let vc = LaunchADViewController()
//        vc.imageView.image = ad.image
//        vc.clickLinkL = ad.link
//        vc.complete = {[weak self] in
//            self?.loadAppRoot()
//        }
//
//        let navi = BaseNavigationController.init(rootViewController: vc)
//        navi.navigationBar.isHidden = true
//        window?.rootViewController = navi
//        window?.makeKeyAndVisible()
    }
    
    func loadSplashAD() -> LaunchADViewController.ADModel? {
        
//        if let data = Preference.App.LaunchDiagram.json{
//
//            let adModel = NewsModel.modelWith(json: data)
//            if let imgUrl = adModel.imageurl.first {//有广告数据
//                if let cacheImage = SDImageCache.shared().imageFromDiskCache(forKey: imgUrl) {//看下有没有缓存好的图片
//                    let model = LaunchADViewController.ADModel.init(image: cacheImage, link: adModel.link)
//                    // 使用之后就移除这个广告缓存
//                    Preference.App.LaunchDiagram.setValue(any: nil)
//                    return model
//                }else{
//                    // 图片未下载成功，这次不显示，先下载图片
//                    self.downloadAndCache(imageUrl: imgUrl)
//                }
//
//            }
//        }
        return nil
    }
    
    /// 请求开屏图
    fileprivate func requestLaunchDiagram(){
        
//        API.D.getAd(area: YRAD.Location.manager.areaID, id: .splash) {[weak self] (response) in
//
//            guard let `self` = self else {return}
//
//            if let data = response.data {
//
//                let status = data["status"]["status"].intValue
//                let union_status = data["status"]["union_status"].intValue
//
//                if status == 1 {//使用自己的广告，获取内容
//                    let ads = data["data"].arrayValue
//                    if let ad = ads.first {
//                        Preference.App.LaunchDiagram.cacheJSON(ad)
//                        let adModel = NewsModel.modelWith(json: ad)
//
//                        if let imgUrl = adModel.imageurl.first {//下载这个图片，供下次启动时用
//                            self.downloadAndCache(imageUrl: imgUrl)
//                        }
//
//                    }
//                }else if union_status == 1 {//使用联盟广告
//
//                }
//            }
//        }
        
    }
    
    /// 下载并缓存图片
    fileprivate func downloadAndCache(imageUrl:String) {
        
//        DispatchQueue.global().async {
//            if let imgUrl = URL.init(string: imageUrl),
//                let imgData = try? Data.init(contentsOf: imgUrl) {
//
//                SDImageCache.shared().storeImageData(toDisk: imgData, forKey: imageUrl)
//                YRLog("图片已下载")
//            }
//        }
    }
}
